﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace TS_XY_Train_Repaire.Locomotive.Plane
{
    public partial class Locomotive_Plan_Schedule_Month : DevExpress.XtraEditors.XtraForm
    {
        public Locomotive_Plan_Schedule_Month()
        {
            InitializeComponent();
        }

        private void Locomotive_Plan_Schedule_Month_FormClosing(object sender, FormClosingEventArgs e)
        {
            TS_Win_Locomotive_MainForm.htActionItem.Remove(this.Name);
        }

        private void bt_Create_Click(object sender, EventArgs e)
        {
            if (cb_Month.Text.Trim().Length > 0 && cb_Year.Text.Trim().Length > 0)
            {
                int _iMaxDay = DateTime.DaysInMonth(Convert.ToInt32(cb_Year.Text), Convert.ToInt32(cb_Month.Text));
                if (_iMaxDay < 31)
                {
                    gb_f_d31.Visible = false;
                    gb_f_w31.Visible = false;
                }
                if (_iMaxDay < 30)
                {
                    gb_f_d30.Visible = false;
                    gb_f_w30.Visible = false;
                }
                if (_iMaxDay < 29)
                {
                    gb_f_d29.Visible = false;
                    gb_f_w29.Visible = false;
                }
                DateTime _dt = new DateTime();
                for (int i = 1; i <= _iMaxDay; i++)
                {
                    _dt = Convert.ToDateTime(cb_Year.Text + '-' + cb_Month.Text + '-' + i.ToString().PadLeft(2, '0'));
                    foreach (DevExpress.XtraGrid.Views.BandedGrid.GridBand _cl in bgv_Main.Bands)
                    {
                        TS_Win_Class._SetBand(_cl, "gb_f_w" + i.ToString().PadLeft(2, '0'), TS_Win_Class._GetWeekString(_dt));
                        TS_Win_Class._SetBandColor(_cl, "gb_f_d" + i.ToString().PadLeft(2, '0'), TS_Win_Class._GetWeekString(_dt));
                    }
                }
                _LoadSchedule();
            }
            else
            {
                gc_Main.DataSource = null;
                MessageBox.Show("请选择正确的年月份！");
            }
        }
        private void _LoadSchedule()
        {
            #region//--计算排程表--//
            int _iMaxDay = DateTime.DaysInMonth(Convert.ToInt32(cb_Year.Text), Convert.ToInt32(cb_Month.Text));
            DateTime _dStime = Convert.ToDateTime(cb_Year.Text + "-" + cb_Month.Text + "-01 00:00:01");
            DateTime _dEtime = Convert.ToDateTime(cb_Year.Text + "-" + cb_Month.Text + "-" + _iMaxDay.ToString().PadLeft(2, '0') + " 23:59:59");
            string _strTime = " between '" + cb_Year.Text + "-" + cb_Month.Text + "-01 00:00:01' and '" + cb_Year.Text + "-" + cb_Month.Text + "-"+_iMaxDay.ToString().PadLeft(2,'0')+" 23:59:59'";
            string strSQL = "delete TS_TR_TMP_Work_Schedule where f_workerid=" + TS_Win_Locomotive_MainForm.pUserInfoMain.GuId;
            TS_Win_Class.MySqlCom(strSQL);
            //strSQL = "select f_id,f_rpname,f_rpnum,f_stname,f_type,(select f_name from TS_S_T_P_RailwayStations where f_id=(select f_arsid from TS_S_T_P_Train_List where f_id=TS_TR_BU_Work_Main.f_trainid)) as f_rsname,f_tcname,f_ttname,f_name,f_pitime,f_pstime,f_potime,f_petime,f_pltime from TS_TR_BU_Work_Main where f_del=0 and ((f_state in (select f_id from TS_S_T_S_RP_DataState where f_del=0 and f_state in (-1)) and (f_pitime " + _strTime + " or f_pltime " + _strTime + ")) or (f_state in (select f_id from TS_S_T_S_RP_DataState where f_del=0 and f_state not in (-1,9)) and (f_itime " + _strTime + " or f_ltime " + _strTime + "))) order by f_pitime asc";
            strSQL = "select f_id,f_rpname,f_rpnum,f_stname,f_type,(select f_name from TS_S_T_P_RailwayStations where f_id=(select f_arsid from TS_S_T_P_Train_List where f_id=TS_TR_BU_Work_Main.f_trainid)) as f_rsname,f_tcname,f_ttname,f_name,f_pitime,f_pstime,f_potime,f_petime,f_pltime from TS_TR_BU_Work_Main where f_del=0 and (f_pitime " + _strTime + " or f_pltime " + _strTime + ") and f_type=0 order by f_pitime asc";
            SqlConnection conn = new SqlConnection(TS_Win_Class.GetSQlConnStr());
            conn.Open();
            SqlCommand comm = new SqlCommand(strSQL, conn);
            SqlDataReader read = comm.ExecuteReader();
            SqlConnection conn1 = new SqlConnection(TS_Win_Class.GetSQlConnStr());
            conn1.Open();
            SqlCommand comm1 = new SqlCommand("select getdate()", conn1);
            SqlDataReader read1 = comm1.ExecuteReader();
            string _sday = "";
            while (read.Read())
            {
                string _Filed = "f_bmwid,f_rpname,f_rpnum,f_stname,f_type,f_rsname,f_tcname,f_ttname,f_name,f_pitime,f_pstime,f_potime,f_petime,f_pltime";
                string _Value = read["f_id"].ToString()+",'" + read["f_rpname"].ToString() + "','" + read["f_rpnum"].ToString() + "',' ',0,'" + read["f_rsname"].ToString() + "','" + read["f_tcname"].ToString() + "','" + read["f_ttname"].ToString() + "','" + read["f_name"].ToString() + "','" + read["f_pitime"].ToString() + "','" + read["f_pstime"].ToString() + "','" + read["f_potime"].ToString() + "','" + read["f_petime"].ToString() + "','" + read["f_pltime"].ToString() + "'";
                read1.Close();
                strSQL = "select datediff(day,'" + cb_Year.Text + "-" + cb_Month.Text + "-01 00:00:01',f_pstime)as f_dayss,datediff(day,'" + cb_Year.Text + "-" + cb_Month.Text + "-" + _iMaxDay.ToString().PadLeft(2, '0') + " 23:59:59',f_pstime)as f_dayse,datediff(day,'" + cb_Year.Text + "-" + cb_Month.Text + "-01 00:00:01',f_petime)as f_dayes,datediff(day,'" + cb_Year.Text + "-" + cb_Month.Text + "-" + _iMaxDay.ToString().PadLeft(2, '0') + " 23:59:59',f_petime)as f_dayee,day(f_pstime) as f_day,(select f_string from TS_S_T_S_ColorList where f_id =(select f_cid from TS_S_T_S_RP_Name_Dictionary where f_id=(select f_ndid from TS_TR_PS_Work_Main_Day where f_id=TS_TR_BU_Work_Main_Day.f_mwdid))) as f_color,(select f_name from TS_S_T_S_RP_Name_Dictionary where f_id=(select f_ndid from TS_TR_PS_Work_Main_Day where f_id=TS_TR_BU_Work_Main_Day.f_mwdid)) as f_ndname,f_name,f_pstime,f_petime,f_length from TS_TR_BU_Work_Main_Day where f_del=0 and f_bmwid=" + read["f_id"].ToString() + " and (f_pstime " + _strTime + " or f_petime " + _strTime + ") order by f_order asc";
                //MessageBox.Show(strSQL);
                comm1 = new SqlCommand(strSQL, conn1);
                read1 = comm1.ExecuteReader();
                while (read1.Read())
                {
                    if ((int)read1["f_dayss"]<0)
                    {
                        for (int n= (int)read1["f_dayss"];n< (int)read1["f_dayss"]+ (int)read1["f_length"];n++)
                        {
                            //if (n >= 0)
                            //{
                            //    _sday = ((DateTime)read1["f_pstime"]).AddDays(n).Day.ToString().PadLeft(2, '0');
                            //    if (_Filed.IndexOf("f_d" + _sday) > 0)
                            //    {
                            //        MessageBox.Show("机车号" + read["f_ttname"].ToString() + read["f_name"].ToString() + " 工序 " + read1["f_name"].ToString() + "时间分配出现错误！-1");
                            //    }
                            //    else
                            //    {
                            //        _Filed += ",f_d" + _sday + ",f_c" + _sday;
                            //        _Value += ",'" + read1["f_ndname"].ToString() + "','" + read1["f_color"].ToString() + "'";
                            //    }
                            //}
                            if (n >= 0)
                            {
                                if (_Filed.IndexOf("f_d" + (n+1).ToString().PadLeft(2,'0')) > 0)
                                {
                                    MessageBox.Show("机车号" + read["f_ttname"].ToString() + read["f_name"].ToString() + " 工序 " + read1["f_name"].ToString() + "时间分配出现错误！-1");
                                }
                                else
                                {
                                    _Filed += ",f_d" + (n + 1).ToString().PadLeft(2, '0') + ",f_c" + (n + 1).ToString().PadLeft(2, '0');
                                    _Value += ",'" + read1["f_ndname"].ToString() + "','" + read1["f_color"].ToString() + "'";
                                }
                            }
                        }
                    }
                    else if ((int)read1["f_dayee"] > 0)
                    {
                        for (int n = (int)read1["f_dayse"]; n <=0; n++)
                        {
                            //_sday = ((DateTime)read1["f_pstime"]).AddDays(n - 1).Day.ToString().PadLeft(2, '0');
                            //if (_Filed.IndexOf("f_d" + _sday) > 0)
                            //{
                            //    MessageBox.Show("机车号" + read["f_ttname"].ToString() + read["f_name"].ToString() + " 工序 " + read1["f_name"].ToString() + "时间分配出现错误！-2");
                            //}
                            //else
                            //{
                            //    _Filed += ",f_d" + _sday + ",f_c" + _sday;
                            //    _Value += ",'" + read1["f_ndname"].ToString() + "','" + read1["f_color"].ToString() + "'";
                            //}
                            _sday = _dEtime.AddDays(n).Day.ToString().PadLeft(2, '0');
                            if (_Filed.IndexOf("f_d" + _sday) > 0)
                            {
                                MessageBox.Show("机车号" + read["f_ttname"].ToString() + read["f_name"].ToString() + " 工序 " + read1["f_name"].ToString() + "时间分配出现错误！-2");
                            }
                            else
                            {
                                _Filed += ",f_d" + _sday + ",f_c" + _sday;
                                _Value += ",'" + read1["f_ndname"].ToString() + "','" + read1["f_color"].ToString() + "'";
                            }
                        }

                    }
                    else
                    {
                        for (int n = 0; n < (int)read1["f_length"]; n++)
                        {
                            _sday = ((DateTime)read1["f_pstime"]).AddDays(n).Day.ToString().PadLeft(2, '0');
                            if (_Filed.IndexOf("f_d" + _sday) > 0)
                            {
                                MessageBox.Show("机车号" + read["f_ttname"].ToString() + read["f_name"].ToString() + " 工序 " + read1["f_name"].ToString() + "时间分配出现错误！-3"+" "+n.ToString());
                            }
                            else
                            {
                                _Filed += ",f_d" + _sday + ",f_c" + _sday;
                                _Value += ",'" + read1["f_ndname"].ToString() + "','" + read1["f_color"].ToString() + "'";
                            }
                        }
                    }
                }
                strSQL = "insert into TS_TR_TMP_Work_Schedule(" + _Filed + ",f_del,f_workerid) values(" + _Value + ",0," + TS_Win_Locomotive_MainForm.pUserInfoMain.GuId + ")";
                //MessageBox.Show(strSQL);
                TS_Win_Class.MySqlCom(strSQL);
            }
            read1.Close();
            conn1.Close();
            conn1.Dispose();
            read.Close();
            conn.Close();
            conn.Dispose();
            #endregion
            strSQL = "select row_number() over (order by f_id) as f_row,*,CONVERT(varchar(100), f_pitime, 23) as f_pitime,CONVERT(varchar(100), f_potime, 23) as f_potime from TS_TR_TMP_Work_Schedule where f_del=0 and f_workerid=" + TS_Win_Locomotive_MainForm.pUserInfoMain.GuId;
            DataTable dt = new DataTable();
            TS_Win_Class.FilledDataTable(strSQL,dt);
            gc_Main.DataSource = dt;
        }
        private void Locomotive_Plan_Schedule_Month_Load(object sender, EventArgs e)
        {
            #region//--初始化色块规则--//
            DevExpress.XtraEditors.FormatConditionRuleValue[,] fcr_Main = new FormatConditionRuleValue[32,9];
            for (int x = 1; x < 32; x++)
            {
                for (int y = 1; y < 9; y++)
                {
                    fcr_Main[x, y] = new DevExpress.XtraEditors.FormatConditionRuleValue();
                    fcr_Main[x, y].Appearance.Options.UseBackColor = true;
                    fcr_Main[x, y].Condition = DevExpress.XtraEditors.FormatCondition.Equal;
                    switch(y)
                    {
                        case 1:
                            fcr_Main[x, y].Appearance.BackColor = System.Drawing.Color.White;
                            fcr_Main[x, y].Value1 = "White";
                            break;
                        case 2:
                            fcr_Main[x, y].Appearance.BackColor = System.Drawing.Color.Gray;
                            fcr_Main[x, y].Value1 = "Gray";
                            break;
                        case 3:
                            fcr_Main[x, y].Appearance.BackColor = System.Drawing.Color.Red;
                            fcr_Main[x, y].Value1 = "Red";
                            break;
                        case 4:
                            fcr_Main[x, y].Appearance.BackColor = System.Drawing.Color.Yellow;
                            fcr_Main[x, y].Value1 = "Yellow";
                            break;
                        case 5:
                            fcr_Main[x, y].Appearance.BackColor = System.Drawing.Color.LightBlue;
                            fcr_Main[x, y].Value1 = "LightBlue";
                            break;
                        case 6:
                            fcr_Main[x, y].Appearance.BackColor = System.Drawing.Color.Magenta;
                            fcr_Main[x, y].Value1 = "Magenta";
                            break;
                        case 7:
                            fcr_Main[x, y].Appearance.BackColor = System.Drawing.Color.Cyan;
                            fcr_Main[x, y].Value1 = "Cyan";
                            break;
                        case 8:
                            fcr_Main[x, y].Appearance.BackColor = System.Drawing.Color.Green;
                            fcr_Main[x, y].Value1 = "Green";
                            break;
                    }
                }
            }
            DevExpress.XtraGrid.GridFormatRule _gfr = new DevExpress.XtraGrid.GridFormatRule();
            for (int i = 1; i < 32; i++)
            {
                for (int n = 1; n < 9; n++)
                {
                    _gfr = new DevExpress.XtraGrid.GridFormatRule();
                    _gfr.Column = this.bgv_Main.Columns["f_c" + i.ToString().PadLeft(2, '0')];
                    _gfr.ColumnApplyTo = this.bgv_Main.Columns["f_d" + i.ToString().PadLeft(2, '0')];
                    _gfr.Name = "Format_" + i.ToString().PadLeft(2, '0') + "_" + n.ToString();
                    _gfr.Rule = fcr_Main[i, n];
                    bgv_Main.FormatRules.Add(_gfr);
                }
            }
            gc_Main.Refresh();
            #endregion
            cb_Year.Text = DateTime.Now.Year.ToString();
            cb_Month.Text = DateTime.Now.Month.ToString().PadLeft(2,'0');
        }

        private void bt_Exp_PDF_Click(object sender, EventArgs e)
        {
            bgv_Main.ExportToPdf(TS_Win_Class._EXP_Direct + cb_Year.Text + "年" + cb_Month.Text + "月份排程表.pdf");
            MessageBox.Show("文件导出为 " + TS_Win_Class._EXP_Direct + cb_Year.Text + "年" + cb_Month.Text + "月份排程表.pdf");
        }

        private void gc_Main_DoubleClick(object sender, EventArgs e)
        {
            if (bgv_Main.SelectedRowsCount>0)
            {
                Locomotive_Train_Gant_Map _uc = new Locomotive_Train_Gant_Map();
                _uc._LoadID = bgv_Main.GetFocusedRowCellValue("f_bmwid").ToString();
                _uc._LoadName = bgv_Main.GetFocusedRowCellValue("f_ttname").ToString()+ bgv_Main.GetFocusedRowCellValue("f_name").ToString();
                _uc.ShowDialog();
            }
        }

        private void bt_Exp_Excel_Click(object sender, EventArgs e)
        {
            DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
            bgv_Main.ExportToXlsx(TS_Win_Class._EXP_Direct+ cb_Year.Text+"年"+ cb_Month.Text + "月份排程表.xlsx");
            MessageBox.Show("文件导出为 "+TS_Win_Class._EXP_Direct + cb_Year.Text + "年" + cb_Month.Text + "月份排程表.xlsx");
        }

        private void gc_Main_Click(object sender, EventArgs e)
        {

        }
    }
}